package com.future;

/**
 * Description: 931. 下降路径最小和
 *
 * @author weiruibai.vendor
 * Date: 2023/2/17 16:49
 */
public class Solution_931 {

    public static void main(String[] args) {

    }


    public int minFallingPathSum(int[][] matrix) {
        int N = matrix.length;
        int M = matrix[0].length;
        int ans = Integer.MAX_VALUE;
        int[][] dp = new int[N][M];
        for (int j = 0; j < M; j++) {
            dp[N - 1][j] = matrix[N - 1][j];
        }
        for (int i = N - 2; i >= 0; i--) {
            for (int j = 0; j < M; j++) {
                int min = dp[i + 1][j];
                if (j > 0) {
                    min = Math.min(min, dp[i + 1][j - 1]);
                }
                if (j < M - 1) {
                    min = Math.min(min, dp[i + 1][j + 1]);
                }
                dp[i][j] = min + matrix[i][j];
            }
        }
        for (Integer num : dp[0]) {
            ans = Math.min(num, ans);
        }
        return ans;
    }
}
